package com.bringspring.system.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.RandomUtil;
import com.bringspring.common.util.wxutil.HttpUtil;
import com.bringspring.system.base.entity.EmailConfigEntity;
import com.bringspring.system.base.entity.SysConfigEntity;
import com.bringspring.system.base.exception.BaseException;
import com.bringspring.system.base.model.systemconfig.*;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.message.entity.QyWebChatModel;
import com.bringspring.system.message.model.message.DingTalkModel;
import com.bringspring.system.message.util.DingTalkUtil;
import com.bringspring.system.message.util.QyWebChatUtil;
import com.bringspring.system.permission.model.user.form.UserUpAdminForm;
import com.bringspring.system.permission.model.user.vo.UserAdminVO;
import com.bringspring.system.permission.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * 系统配置
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月27日 上午9:18
 */
@Api(tags = "系统配置", value = "SysConfig")
@RestController
@RequestMapping("/api/system/SysConfig")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private UserService userService;

    /**
     * 查询全部配置列表
     *
     * @return ignore
     */
    @ApiOperation("列表")
    @GetMapping
    public ActionResult list() {
        List<SysConfigEntity> list = sysConfigService.getList();
        HashMap<String, String> map = new HashMap<>(16);
        for (SysConfigEntity sys : list) {
            map.put(sys.getKeyName(), sys.getKeyValue());
        }
        SysConfigModel sysConfigModel = JsonUtil.getJsonToBean(map, SysConfigModel.class);
        return ActionResult.success(sysConfigModel);
    }

    /**
     * 列表
     *
     * @return ignore
     */
    @ApiOperation("列表")
    @GetMapping("/getConfigByKeyName/{keyName}")
    public ActionResult getConfigByKeyName(@PathVariable("keyName") String keyName) throws BaseException {
        SysConfigEntity sysConfigEntity = sysConfigService.getConfigByKeyName(keyName);
        return ActionResult.success(sysConfigEntity);
    }
    /**
     * 通过分类获取列表
     *
     * @return ignore
     */
    @ApiOperation("列表")
    @GetMapping("/getConfigListByCategory/{category}")
    public ActionResult getConfigListByCategory(@PathVariable("category") String category) throws BaseException {
        List<SysConfigEntity> sysConfigList = sysConfigService.getConfigListByCategory(category);
        List<SysConfigVo> list = JsonUtil.getJsonToList(sysConfigList,SysConfigVo.class);
        return ActionResult.success(list);
    }
    /**
     * 保存设置
     *
     * @param sysConfigModel 系统配置模型
     * @return ignore
     */
    @ApiOperation("更新系统配置")
    @PutMapping
    public ActionResult saveConfig(@RequestBody SysConfigListVO sysConfigModel) {
        List<SysConfigEntity> entitys = new ArrayList<>();

        for (SysConfigModelNew entry : sysConfigModel.getList()) {
            SysConfigEntity entity = new SysConfigEntity();
            entity.setId(RandomUtil.uuId());
            entity.setName(entry.getName());
            entity.setKeyName(entry.getKey());
            entity.setKeyValue(entry.getValue());
            entity.setCategory(sysConfigModel.getCategory());
            entitys.add(entity);
        }
        try {
            sysConfigService.saveBatch(entitys,sysConfigModel.getCategory());
        } catch (com.bringspring.system.base.exception.BaseException e) {
            e.printStackTrace();
        }
        return ActionResult.success(MsgCode.SU005.get());
    }
    /**
     * 保存设置单个设置
     *
     * @param entity 系统配置模型
     * @return ignore
     */
    @ApiOperation("更新系统配置")
    @PutMapping("/saveByKeyName")
    public ActionResult saveConfig(@RequestBody SysConfigEntity entity) {
        sysConfigService.save(entity);
        return ActionResult.success(MsgCode.SU005.get());
    }
    /**
     * 邮箱账户密码验证
     *
     * @param emailTestForm 邮箱测试模型
     * @return ignore
     */
    @ApiOperation("邮箱连接测试")
    @PostMapping("/Email/Test")
    public ActionResult checkLogin(@RequestBody EmailTestForm emailTestForm) {
        EmailConfigEntity entity = JsonUtil.getJsonToBean(emailTestForm, EmailConfigEntity.class);
        String result = sysConfigService.checkMainLogin(entity);
        if ("true".equals(result)) {
            return ActionResult.success(MsgCode.SU017.get());
        } else {
            return ActionResult.fail(result);
        }
    }


    //=====================================测试企业微信、钉钉的连接=====================================

    /**
     * 测试企业微信配置的连接功能
     *
     * @param type           0-发送消息,1-同步组织
     * @param qyWebChatModel 企业微信模型
     * @return ignore
     */
    @ApiOperation("测试企业微信配置的连接")
    @PostMapping("{type}/testQyWebChatConnect")
    public ActionResult testQyWebChatConnect(@PathVariable("type") String type, @RequestBody @Valid QyWebChatModel qyWebChatModel) {
        JSONObject retMsg = new JSONObject();
        // 测试发送消息、组织同步的连接
        String corpId = qyWebChatModel.getQyhCorpId();
        String agentSecret = qyWebChatModel.getQyhAgentSecret();
        String corpSecret = qyWebChatModel.getQyhCorpSecret();
        // 测试发送消息的连接
        if ("0".equals(type)) {
            retMsg = QyWebChatUtil.getAccessToken(corpId, agentSecret);
            if (HttpUtil.isWxError(retMsg)) {
                return ActionResult.fail("测试发送消息的连接失败：" + retMsg.getString("errmsg"));
            }
            return ActionResult.success("测试发送消息连接成功");
        } else if ("1".equals(type)) {
            retMsg = QyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (HttpUtil.isWxError(retMsg)) {
                return ActionResult.fail("测试组织同步的连接失败：" + retMsg.getString("errmsg"));
            }
            return ActionResult.success("测试组织同步连接成功");
        }
        return ActionResult.fail("测试连接类型错误");
    }

    /**
     * 测试钉钉配置的连接功能
     *
     * @param dingTalkModel 钉钉模板
     * @return ignore
     */
    @ApiOperation("测试钉钉配置的连接")
    @PostMapping("/testDingTalkConnect")
    public ActionResult testDingTalkConnect(@RequestBody @Valid DingTalkModel dingTalkModel) {
        JSONObject retMsg = new JSONObject();
        // 测试钉钉配置的连接
        String appKey = dingTalkModel.getDingSynAppKey();
        String appSecret = dingTalkModel.getDingSynAppSecret();
        ///
//        String agentId = dingTalkModel.getDingAgentId();
        // 测试钉钉的连接
        retMsg = DingTalkUtil.getAccessToken(appKey, appSecret);
        if (!retMsg.getBoolean("code")) {
            return ActionResult.fail("测试钉钉连接失败：" + retMsg.getString("error"));
        }

        return ActionResult.success("测试钉钉连接成功");
    }

    @ApiOperation("获取管理员集合")
    @GetMapping("/getAdminList")
    public ActionResult<List<UserAdminVO>> getAdminList(){
        List<UserAdminVO> admins = JsonUtil.getJsonToList(userService.getAdminList(), UserAdminVO.class);
        return ActionResult.success(admins);
    }

    @ApiOperation("获取管理员集合")
    @PutMapping("/setAdminList")
    public ActionResult<String> setAdminList(@RequestBody UserUpAdminForm userUpAdminForm){
        userService.setAdminListByIds(userUpAdminForm.getAdminIds());
        return ActionResult.success(MsgCode.SU004.get());
    }

}
